import { defineStore } from "pinia";
import { store } from "@/store";
import { listData, getData, getDicts } from "@/api/system/dict/data";
import { getStore, getToken, setStore } from "@/utils/auth";
export const useDictStore = defineStore("dict", () => {
  let dictDataAllList = ref<DictData[]>([
    {
      dictLabel: "",
      dictValue: "",
      dictType: "",
    },
  ]);

  /**
   *
   * @returns 获取全部字典
   */
  function getDataList() {
    return new Promise((resolve, reject) => {
      const dictAllList: any[] = getStore({ name: "dictDataAll-list" });
      if (dictAllList && dictAllList.length > 0) {
        dictDataAllList.value = dictAllList;
        resolve(dictAllList);
      } else {
        listData(null)
          .then((res: any) => {
            if (res.rows) {
              dictDataAllList.value = res.rows;
              resolve(res.rows);
            }
          })
          .catch((error) => {
            reject(error);
          });
      }
    });
  }
  /** 将获取到的字典list封装成 type label的map */
  function groupedDataMap() {
    const groups = <DictData>{};
    dictDataAllList.value.forEach((item) => {
      const dictType: string = item.dictType;
      if (!groups[dictType]) {
        groups[dictType] = [];
      }
      groups[dictType].push(item);
    });
    return groups;
    // return Object.keys(groups).map((key) => ({ key, items: groups[key] }));
  }

  /** 根据字典类型进行分类 返回Map*/
  function isTypeGetData(...arrays) {
    const groupedDataMapRet = groupedDataMap();
    let dictDataMap = <DictData>{};
    arrays.forEach((item) => {
      if (!dictDataMap[item]) {
        dictDataMap[item] = [];
      }
      const aa = groupedDataMapRet[item];
      dictDataMap[item] = aa;
    });
    return dictDataMap;
  }

  return {
    dictDataAllList,
    getDataList,
    isTypeGetData,
    groupedDataMap,
  };
});

export function useDictStoreHook() {
  return useDictStore(store);
}
